using System.Collections.Generic;
using Close.io.Client;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Close.io.API
{
	public static class TemplateManager
	{
		private const string endPoint = "email_template";
		private static readonly Dictionary<string, string> templateLookupDictionary;

		static TemplateManager()
		{
			templateLookupDictionary = new Dictionary<string, string>();

			var client = new CloseIoClient();
			client.Get(endPoint);
			CloseIoApiResult result = Retry.Do(client.Get, endPoint);

			var responseObject = JsonConvert.DeserializeObject<JObject>(result.Content);
			var templates = responseObject["data"].ToObject<JArray>();

			foreach (JObject template in templates.Children<JObject>())
			{
				string id = template["id"].ToString();
				string name = template["name"].ToString();
				templateLookupDictionary.Add(name, id);
			}
		}

		public static string GetTemplateId(string templateName)
		{
			string templateId;
			templateLookupDictionary.TryGetValue(templateName, out templateId);

			return templateId;
		}
	}
}